﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FatusoAction.Model;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Configuration;
using System.IO.Compression;
using System.Xml.Linq;
using System.Diagnostics;

namespace FatusoAction
{
    public class FilmeAction
    {
        #region [Verifica Títulos]

        public static List<TituloModel> VerificaTitulos(string nomeRelease)
        {
            return VerificaTitulos_AdoroCinema(nomeRelease);
        }

        public static List<TituloModel> VerificaTitulos_AdoroCinema(string nomeRelease)
        {
            try
            {
                string tag = FolderAndXMLAction.RecuperaTagFilme(nomeRelease, TipoRetornoTag.RetornaAmbos);
                string releasePesquisa = tag != "" ? nomeRelease.Substring(0, nomeRelease.IndexOf(tag)): nomeRelease;

                string termoUri = releasePesquisa.Replace(' ', '+');
                string url_busca = "http://www.adorocinema.com/busca/1/?q=" + termoUri;
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url_busca);
                myRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                myRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                myRequest.Method = "GET";

                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream());
                string result = sr.ReadToEnd();
                sr.Close();
                myResponse.Close();


                string resultFiltrado = result;
                resultFiltrado = result.Substring(result.IndexOf("vmargin10t"));
                resultFiltrado = resultFiltrado.Substring(0, resultFiltrado.IndexOf("/filmes/mais-esperados/"));

                string auxPattern = "/filmes/";
                var auxRegex = new Regex(auxPattern, RegexOptions.IgnoreCase);
                MatchCollection auxMatches = auxRegex.Matches(resultFiltrado);
                if (auxMatches.Count == 0)
                    return new List<TituloModel>();

                List<TituloModel> titulos = new List<TituloModel>();
                List<TituloModel> titulosSec = new List<TituloModel>();
                foreach (Match match in auxMatches)
                {
                    string tempMatch = resultFiltrado.Substring(match.Index).Replace(auxPattern, "");
                    //Verifica se é o link correto
                    if (tempMatch.Substring(0, 70).Contains("img"))
                        continue;

                    string nomeFilmeOriginal = tempMatch.Substring(tempMatch.IndexOf('(')+1, tempMatch.IndexOf(')') - tempMatch.IndexOf('(')-1);
                    nomeFilmeOriginal = nomeFilmeOriginal.Replace("<b>", "").Replace("</b>", "");
                    tempMatch = tempMatch.Substring(tempMatch.IndexOf("fs11") + 7);
                    string anoFilme = tempMatch.Substring(0, tempMatch.IndexOf("<br"));

                    if (nomeFilmeOriginal != "" && anoFilme != "" && tag.Contains(anoFilme))
                        titulos.Add(new TituloModel(nomeFilmeOriginal, anoFilme));
                    else if (nomeFilmeOriginal != "" && anoFilme != "")
                        titulosSec.Add(new TituloModel(nomeFilmeOriginal, anoFilme));
                }
                titulos.AddRange(titulosSec);
                return titulos;
            }
            catch (Exception)
            {
                return new List<TituloModel>();
            }
        }

        #endregion

        #region [Download de Episódio]

        public static void DownloadEpisodio(EpisodioModel episodio, TipoVideo tipoVideo, string releaseComando)
        {
            DownloadEpisodio_KatPH(episodio, tipoVideo, releaseComando);
        }

        public static void DownloadEpisodio_KatPH(EpisodioModel episodio, TipoVideo tipoVideo, string releaseComando)
        {
            #region [OLD]
            //string downloadurl = episodio.URLDownload;

            //using (var client = new WebClient())
            //{
            //    var values = new NameValueCollection();
            //    int indexFile = episodio.URLDownload.LastIndexOf('.');
            //    string extension = episodio.URLDownload.Substring(indexFile);

            //    string caminhoDownload = ConfigurationSettings.AppSettings["CaminhoDownloadTorrent"].TrimEnd('\\');
            //    string filename = caminhoDownload;

            //    if (!Directory.Exists(filename)) Directory.CreateDirectory(filename);

            //    filename += "\\" + episodio.Release + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
            //    client.DownloadFile(downloadurl, filename);

            //}
            #endregion

            byte[] result;
            byte[] buffer = new byte[4096];

            WebRequest wr = WebRequest.Create(episodio.URLDownload);
            wr.ContentType = "application/x-bittorrent";
            using (WebResponse response = wr.GetResponse())
            {
                bool gzip = response.Headers["Content-Encoding"] == "gzip";
                var responseStream = gzip
                                        ? new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)
                                        : response.GetResponseStream();

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = responseStream.Read(buffer, 0, buffer.Length);
                        memoryStream.Write(buffer, 0, count);
                    } while (count != 0);

                    result = memoryStream.ToArray();
                }

                var values = new NameValueCollection();
                int indexFile = episodio.URLDownload.LastIndexOf('.');
                string extension = episodio.URLDownload.Substring(indexFile);
                string caminhoDownloadTorrent = ConfigurationSettings.AppSettings["CaminhoDownloadTorrent"].TrimEnd('\\');
                string filenameTorrent = caminhoDownloadTorrent;
                if (!Directory.Exists(filenameTorrent)) Directory.CreateDirectory(filenameTorrent);
                filenameTorrent += "\\" + episodio.Release + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;


                using (BinaryWriter writer = new BinaryWriter(new FileStream(filenameTorrent, FileMode.Create)))
                {
                    writer.Write(result);
                }

                string caminhoDownloadSerie = ConfigurationSettings.AppSettings["CaminhoDownloadSerie"].TrimEnd('\\');

                string caminhoPasta = caminhoDownloadSerie + "\\" + FolderAndXMLAction.RecuperaNomePastaVideo(episodio.Release, tipoVideo);
                if (tipoVideo == TipoVideo.Filme) caminhoPasta += "\\" + releaseComando;

                if (!Directory.Exists(caminhoPasta)) Directory.CreateDirectory(caminhoPasta);

                string caminhoExeBitTorrent = ConfigurationSettings.AppSettings["CaminhoBitTorrent"];
                string argumentos = "/DIRECTORY \"" + caminhoPasta + "\" \"" + filenameTorrent + "\"";

                Process.Start(caminhoExeBitTorrent, argumentos);
            }
        }


        #endregion
    }
}
